﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using debioscoopincdrie.Managers;
using debioscoopincdrie.Model;

namespace debioscoopincdrie.forms
{
    public partial class MainForm : Form
    {
        #region Fields
        private ReservationChecker rc;
        private Thread reservationCheckThread;

        //First tab
        private TabPage tpTickets;
        private TabPage tpReservations;
        private TabPage tpObjects;
        private TabPage tpOthers;
        private TabPage tpAdd;

        private Label lblMovieDescription;

        private ComboBox cbMovies;

        private GroupBox gbMovieTimes;
        private GroupBox gbMovieTickets;
        private GroupBox gbMovieSeats;

        private film currentMovie;
        private planning currentPlanning;

        private Button btnSave;

        private int amountTickets = 0;

        private kaartje[] selectedTickets;

        //Second tab
        private GroupBox gbReservationDetails;

        private NumericUpDown nudReservation;

        //Third tab
        private DataGridView dgv;
        #endregion

        #region Constructors
        public MainForm()
        {
            InitializeComponent();

            Init();

            StartThreads();
        }
        #endregion

        #region Private functions
        private void Init()
        {
            this.Disposed += MainForm_Disposed;

            CreateFirstTab();
            CreateSecondTab();
            CreateThirdTab();
            CreateFourthTab();
        }

        private void CreateFirstTab()
        {
            tpTickets = new TabPage();
            tpTickets.Text = "Kaarten";
            tpTickets.BackColor = Color.White;

            cbMovies = new ComboBox();
            cbMovies.Text = "Selecteer film";
            cbMovies.SetBounds(20, 20, 200, 20);
            cbMovies.SelectedValueChanged += cbMovies_SelectedValueChanged;
            
            cbMovies.Items.Add("Selecteer film");
            foreach (film movie in MovieManager.GetManager().GetMoviesToday())
            {
                cbMovies.Items.Add(movie.naam);
            }
            tpTickets.Controls.Add(cbMovies);

            lblMovieDescription = new Label();
            lblMovieDescription.SetBounds(400, 50, 300, 80);
            tpTickets.Controls.Add(lblMovieDescription);

            gbMovieTimes = new GroupBox();
            gbMovieTimes.Text = "Tijd";
            gbMovieTimes.SetBounds(20, 50, 100, 20);
            gbMovieTimes.AutoSize = true;
            gbMovieTimes.Visible = false;
            tpTickets.Controls.Add(gbMovieTimes);

            gbMovieTickets = new GroupBox();
            gbMovieTickets.Text = "Kaarten";
            gbMovieTickets.AutoSize = true;
            gbMovieTickets.Visible = false;
            tpTickets.Controls.Add(gbMovieTickets);

            gbMovieSeats = new GroupBox();
            gbMovieSeats.Text = "Kies zitplaats";
            gbMovieSeats.AutoSize = true;
            gbMovieSeats.Visible = false;
            tpTickets.Controls.Add(gbMovieSeats);

            tcMain.TabPages.Add(tpTickets);
        }

        private void CreateSecondTab()
        {
            tpReservations = new TabPage();
            tpReservations.Text = "Reserveringen";
            tpReservations.BackColor = Color.White;

            Label lblReservationId = new Label();
            lblReservationId.Text = "Reservering code:";
            lblReservationId.Location = new Point(10, 12);
            tpReservations.Controls.Add(lblReservationId);

            nudReservation = new NumericUpDown();
            nudReservation.Location = new Point(130, 10);
            nudReservation.ValueChanged += btnSearch_Click;
            tpReservations.Controls.Add(nudReservation);

            Button btnSearch = new Button();
            btnSearch.Text = "Zoek";
            btnSearch.Location = new Point(260, 10);
            btnSearch.Click += btnSearch_Click;
            tpReservations.Controls.Add(btnSearch);

            gbReservationDetails = new GroupBox();
            gbReservationDetails.Location = new Point(10, 40);
            gbReservationDetails.Text = "Reservering details";
            gbReservationDetails.Visible = false;
            gbReservationDetails.AutoSize = true;
            tpReservations.Controls.Add(gbReservationDetails);

            tcMain.TabPages.Add(tpReservations);
        }

        private void CreateThirdTab()
        {
            tpObjects = new TabPage();
            tpObjects.Text = "Gevonden/Verloren voorwerpen";
            tpObjects.BackColor = Color.White;

            TabControl tcObjects = new TabControl();
            tcObjects.Location = new Point(20, 20);
            tcObjects.Width = 710;
            tcObjects.Height = 470;
            tcObjects.Selecting += tcObjects_Selecting;

            tpAdd = new TabPage();
            tpAdd.Text = "Toevoegen";
            tcObjects.TabPages.Add(tpAdd);

            Label lblName = new Label();
            lblName.Text = "Voorwerp naam: ";
            lblName.Location = new Point(5, 10);
            tpAdd.Controls.Add(lblName);

            TextBox tbName = new TextBox();
            tbName.Text = "";
            tbName.Name = "tbName";
            tbName.Location = new Point(130, 7);
            tpAdd.Controls.Add(tbName);

            Label lblDescription = new Label();
            lblDescription.Text = "Korte beschrijving:";
            lblDescription.Location = new Point(5, 35);
            tpAdd.Controls.Add(lblDescription);

            TextBox tbDescription = new TextBox();
            tbDescription.Text = "";
            tbDescription.Name = "tbDescription";
            tbDescription.Location = new Point(130, 32);
            tpAdd.Controls.Add(tbDescription);

            Label lblStatus = new Label();
            lblStatus.Text = "Huidge status";
            lblStatus.Location = new Point(5, 60);
            tpAdd.Controls.Add(lblStatus);

            ComboBox cbStatus = new ComboBox();
            cbStatus.Name = "cbStatus";
            cbStatus.Text = "Status";
            cbStatus.Location = new Point(130, 60);
            tpAdd.Controls.Add(cbStatus);
            cbStatus.Items.Add("Status");
            foreach (Enums.ObjectStatus status in Enum.GetValues(typeof(Enums.ObjectStatus)))
            {
                cbStatus.Items.Add(status.ToString());
            }

            Button btnAdd = new Button();
            btnAdd.Text = "Invoeren";
            btnAdd.Location = new Point(130, 85);
            btnAdd.AutoSize = true;
            btnAdd.Click += btnAdd_Click;
            tpAdd.Controls.Add(btnAdd);

            TabPage tpSearch = new TabPage();
            tpSearch.Text = "Zoeken";
            tcObjects.TabPages.Add(tpSearch);

            Label lblFilter = new Label();
            lblFilter.Text = "Filter:";
            lblFilter.Location = new Point(580, 10);
            lblFilter.AutoSize = true;
            tpSearch.Controls.Add(lblFilter);

            TextBox tbFilter = new TextBox();
            tbFilter.Text = string.Empty;
            tbFilter.Location = new Point(580, 35);
            tbFilter.TextChanged += tbFilter_TextChanged;
            tpSearch.Controls.Add(tbFilter);

            dgv = new DataGridView();
            dgv.DataSource = FillData(ObjectManager.GetManager().getAllObjects());
            dgv.AutoSize = false;
            dgv.Width = 480;
            dgv.Height = 420;
            dgv.Location = new Point(10, 10);
            dgv.Refresh();
            dgv.CellClick += dgv_CellClick;
            dgv.ScrollBars = ScrollBars.Vertical;
            
            tpSearch.Controls.Add(dgv);

            tpObjects.Controls.Add(tcObjects);

            tcMain.TabPages.Add(tpObjects);
        }

        private void CreateFourthTab()
        {
            tpOthers = new TabPage();
            tpOthers.Text = "Overige kaarten";
            tpOthers.BackColor = Color.White;

            Label lblType = new Label();
            lblType.Text = "Kaart:";
            lblType.AutoSize = true;
            lblType.Location = new Point(10, 10);
            tpOthers.Controls.Add(lblType);

            ComboBox cbType = new ComboBox();
            cbType.Text = "Selecteer Type";
            cbType.Location = new Point(130, 7);
            cbType.Items.Add("Selecteer Type");
            cbType.Items.Add("Abonnement");
            cbType.Items.Add( "10-kaart");
            cbType.Items.Add( "Bioscoopbon (€7.50)");
            cbType.Items.Add("Bioscoopbon (€10.-)");
            cbType.SelectedValueChanged += cbType_SelectedValueChanged;
            tpOthers.Controls.Add(cbType);        

            tcMain.TabPages.Add(tpOthers);
        }

        void cbType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (sender is ComboBox)
            {
                ComboBox cb = (ComboBox)sender;
                if (cb.SelectedItem.Equals("Abonnement"))
                {
                    OutputManager.GetManager().createAbonnement( "Kortingskaart (50%)", 50, DateTime.Today.AddMonths(1));
                    cb.SelectedIndex = 0;
                    MessageBox.Show("Uw abonnement is afgedrukt!");
                }
                else if (cb.SelectedItem.Equals("10-kaart"))
                {
                    OutputManager.GetManager().createAbonnement("Strippenkaart", 100, DateTime.Today);
                    cb.SelectedIndex = 0;
                    MessageBox.Show("Uw strippenkaart is afgedrukt!");
                }
                else if (cb.SelectedItem.Equals("Bioscoopbon (€7.50)"))
                {
                    OutputManager.GetManager().createBon(7.50);
                    cb.SelectedIndex = 0;
                    MessageBox.Show("Uw bon is afgedrukt!");
                }
                else if (cb.SelectedItem.Equals("Bioscoopbon (€10.-)"))
                {
                    OutputManager.GetManager().createBon(10.0);
                    cb.SelectedIndex = 0;
                    MessageBox.Show("Uw bon is afgedrukt!");
                }
            }
        }

        void tbFilter_TextChanged(object sender, EventArgs e)
        {
            if (sender is TextBox)
            {
                TextBox tb = (TextBox)sender;
                dgv.DataSource = FillData(ObjectManager.GetManager().getObjectsLike(tb.Text));
            }
        }

        void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                dgv.Rows[e.RowIndex].ReadOnly = true;

                if (!dgv.Rows[e.RowIndex].Cells[0].Value.ToString().Equals(string.Empty))
                {
                    voorwerp m_object = ObjectManager.GetManager().getObject(int.Parse(dgv.Rows[e.RowIndex].Cells[0].Value.ToString()));
                    if (dgv.Rows[e.RowIndex].Cells[3].Value.ToString().Equals(Enums.ObjectStatus.gevonden.ToString()))
                    {
                        m_object.m_status = Enums.ObjectStatus.verloren.ToString();   
                    }
                    else if (dgv.Rows[e.RowIndex].Cells[3].Value.ToString().Equals(Enums.ObjectStatus.verloren.ToString()))
                    {
                        m_object.m_status = Enums.ObjectStatus.gevonden.ToString();
                    }
                    DatabaseManager.GetManager().SaveChanges();
                    tcObjects_Selecting(null, null);
                }
            }
            catch
            {
            }
        }

        void tcObjects_Selecting(object sender, TabControlCancelEventArgs e)
        {
            dgv.DataSource = FillData(ObjectManager.GetManager().getAllObjects());
            dgv.Refresh();
        }

        private DataTable FillData( List<voorwerp> m_objects )
        {
            List<string> columnNames = new List<string>();
            columnNames.Add("id");
            columnNames.Add("Naam");
            columnNames.Add("Beschrijving");
            columnNames.Add("Status");

            DataTable dt = new DataTable();

            dt.Columns.Clear();
            foreach (string name in columnNames)
            {
                dt.Columns.Add(name);
            }

            int row = 0;
            foreach (voorwerp m_object in m_objects)
            {
                dt.Rows.Add();
                dt.Rows[row][0] = m_object.id;
                dt.Rows[row][1] = m_object.naam;
                dt.Rows[row][2] = m_object.beschrijving;
                dt.Rows[row][3] = m_object.m_status;
                row++;
            }

            return dt;
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            bool ready = true;
            ComboBox cbStatus = null;
            TextBox tbName = null;
            TextBox tbDescription = null;
            
            foreach (Control control in tpAdd.Controls)
            {
                if (control is ComboBox && control.Name.Equals("cbStatus"))
                {
                    cbStatus = (ComboBox)control;
                    if (cbStatus.SelectedItem == null || cbStatus.SelectedItem.ToString().Equals("Status"))
                    {
                        ready = false;
                        MessageBox.Show("Select a status please");
                    }
                }
                else if (control is TextBox && control.Name.Equals("tbName"))
                {
                    tbName = (TextBox)control;
                    if (tbName.Text.Equals(String.Empty))
                    {
                        ready = false;
                        MessageBox.Show("Please insert a name");
                    }
                }
                else if (control is TextBox && control.Name.Equals("tbDescription"))
                {
                    tbDescription = (TextBox)control;
                    if (control.Text.Equals(String.Empty))
                    {
                        ready = false;
                        MessageBox.Show("Please insert a description");
                    }
                }
            }

            if (ready)
            {
                Enums.ObjectStatus os = (Enums.ObjectStatus)Enum.Parse(typeof(Enums.ObjectStatus), cbStatus.SelectedItem.ToString());
                ObjectManager.GetManager().addObject(tbName.Text, tbDescription.Text, os);
                tbName.Text = string.Empty;
                tbDescription.Text = string.Empty;
                cbStatus.SelectedIndex = 0;
            }
        }

        private void StartThreads()
        {
            rc = new ReservationChecker();
            reservationCheckThread = new Thread(new ThreadStart(rc.start));

            reservationCheckThread.Start();
        }
        #endregion

        #region Events

        void btnSearch_Click(object sender, EventArgs e)
        {
            gbReservationDetails.Controls.Clear();

            if ((int)nudReservation.Value > 0)
            {
                bestelling reservation = ReservationManager.GetManager().getReservation((int)nudReservation.Value);
                if (reservation != null && reservation.soort.Equals(Enums.OrderType.reservering.ToString()))
                {
                    gbReservationDetails.Visible = true;

                    if (!reservation.active)
                    {
                        Label lbl = new Label();
                        lbl.Text = "Deze reservering is geannuleerd";
                        lbl.Location = new Point(10, 45);
                        lbl.AutoSize = true;
                        gbReservationDetails.Controls.Add(lbl);
                    }
                    else
                    {
                        Label lblMovie = new Label();
                        if (reservation.planning != null)
                        {
                            lblMovie.Text = "Film: " + reservation.planning.film.naam;
                            lblMovie.Location = new Point(10, 20);
                            lblMovie.AutoSize = true;
                            gbReservationDetails.Controls.Add(lblMovie);
                        }

                        Label lblTicketCount = new Label();
                        lblTicketCount.Text = "Ticket(s): #" + reservation.kaartje.Count();
                        lblTicketCount.Location = new Point(10, 45);
                        gbReservationDetails.Controls.Add(lblTicketCount);

                        if (reservation.betaald && reservation.afgehaald)
                        {
                            Label lblPayed = new Label();
                            lblPayed.Text = "Deze reservering is opgehaald!";
                            lblPayed.Location = new Point(10, 70);
                            lblPayed.AutoSize = true;
                            gbReservationDetails.Controls.Add(lblPayed);
                        }
                        else
                        {
                            Label lblCosts = new Label();
                            lblCosts.Text = "Bedrag: €" + reservation.totaal_bedrag;
                            lblCosts.Location = new Point(10, 70);
                            lblCosts.AutoSize = true;
                            gbReservationDetails.Controls.Add(lblCosts);

                            Button btnPay = new Button();
                            btnPay.Text = "Betaal";
                            btnPay.Location = new Point(130, 70);
                            btnPay.AutoSize = true;
                            btnPay.Click += btnPay_Click;
                            gbReservationDetails.Controls.Add(btnPay);

                            Button btnCancel = new Button();
                            btnCancel.Text = "Annuleer";
                            btnCancel.Location = new Point(260, 70);
                            btnCancel.AutoSize = true;
                            btnCancel.Click += btnCancel_Click;
                            gbReservationDetails.Controls.Add(btnCancel);
                        }
                    }
                    
                }
                else
                {
                    gbReservationDetails.Visible = false;
                }
            }
            else
            {
                gbReservationDetails.Visible = false;
            }
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            if (nudReservation.Value > 0)
            {
                ReservationManager.GetManager().cancelReservation((int)nudReservation.Value);
                btnSearch_Click(sender, e);
            }
        }

        void btnPay_Click(object sender, EventArgs e)
        {
            if (nudReservation.Value > 0)
            {
                ReservationManager.GetManager().pickUpReservation((int)nudReservation.Value);
                bestelling reservation = ReservationManager.GetManager().getReservation((int)nudReservation.Value);
                MessageBox.Show("Klant heeft €" + reservation.totaal_bedrag + " betaald");
                for (int i = 0; i < reservation.kaartje.Count; ++i)
                {
                    OutputManager.GetManager().createTicket((int)nudReservation.Value, reservation.kaartje.ToList()[i].kaartjeid);
                }
                btnSearch_Click(sender, e);
            }
        }

        void cbMovies_SelectedValueChanged(object sender, EventArgs e)
        {
            currentMovie = MovieManager.GetManager().GetMovie(cbMovies.SelectedItem.ToString());
            if (currentMovie != null)
            {
                gbMovieTimes.Controls.Clear();
                gbMovieTimes.Visible = true;
                gbMovieTickets.Visible = false;
                gbMovieSeats.Visible = false;
                lblMovieDescription.Visible = true;

                lblMovieDescription.Text = "Omschrijving: " + currentMovie.omschrijving;
                lblMovieDescription.Text += "\r\n\r\nGenres: | ";
                foreach (genre genre in currentMovie.genre)
                {
                    lblMovieDescription.Text += genre.genre1 + " | ";
                }

                int prevX = 0;
                int prevY = 0;
                int count = 0;
                foreach (planning planning in currentMovie.planning.ToList())
                {
                    if (planning.datum == DateTime.Today.Date && planning.tijd >= DateTime.Now.TimeOfDay)
                    {
                        count++;

                        if (count == 4)
                        {
                            count = 0;
                            prevX = 0;
                            prevY += 25;
                        }

                        RadioButton rbMovietime = new RadioButton();
                        rbMovietime.Text = planning.tijd.ToString();
                        rbMovietime.Location = new Point(20 + prevX, 20 + prevY);
                        rbMovietime.CheckedChanged += rbMovietime_CheckedChanged;

                        prevX += 110;
                        gbMovieTimes.Controls.Add(rbMovietime);
                    }
                }
            }
            else
            {
                gbMovieTimes.Controls.Clear();
                gbMovieTimes.Visible = false;
                gbMovieTickets.Visible = false;
                gbMovieSeats.Visible = false;
                lblMovieDescription.Visible = false;
            }
        }

        void rbMovietime_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton raSender = (RadioButton)sender;
            if (raSender.Checked)
            {
                gbMovieTickets.Controls.Clear();

                currentPlanning = PlanningManager.GetManager().GetPlanning(currentMovie.film_id, DateTime.Now, TimeSpan.Parse(raSender.Text));
                int avaibleSeats = MovieManager.GetManager().GetAvaibleSeats(currentMovie.naam, DateTime.Now, TimeSpan.Parse(raSender.Text));

                gbMovieTickets.Visible = true;
                gbMovieTickets.SetBounds(20, gbMovieTimes.Bounds.Y + gbMovieTimes.Bounds.Height + 20, 150, 20);

                int prevY = 0;
                foreach (kaart_soort ticket in TicketManager.GetManager().GetTicketTypes())
                {
                    Label lblTicketName = new Label();
                    lblTicketName.Text = ticket.kaart_soort_naam.Replace("Kaart", " €") + getPriceForTicket( currentMovie, ticket ).ToString("0.00");
                    lblTicketName.Location = new Point(5, 20 + prevY);

                    ComboBox cbTicket = new ComboBox();
                    cbTicket.Name = ticket.kaart_soort_naam;
                    cbTicket.Text = "aantal tickets";
                    cbTicket.Location = new Point(130, 20 + prevY);
                    for (int i = 0; i <= avaibleSeats; i++)
                    {
                        cbTicket.Items.Add(i);
                    }
                    cbTicket.SelectedValueChanged += cbTicket_SelectedValueChanged;
                    prevY += 25;
                    gbMovieTickets.Controls.Add(lblTicketName);
                    gbMovieTickets.Controls.Add(cbTicket);
                }
            }
        }

        void cbTicket_SelectedValueChanged(object sender, EventArgs e)
        {
            amountTickets = 0;
            foreach (Control control in gbMovieTickets.Controls)
            {
                if (control is ComboBox)
                {
                    if ( !control.Text.Equals("aantal tickets"))
                    {
                        amountTickets += int.Parse(control.Text);
                    }
                }
            }

            gbMovieSeats.Visible = true;
            gbMovieSeats.SetBounds(20 + gbMovieTickets.Bounds.X + gbMovieTickets.Bounds.Width, gbMovieTimes.Bounds.Y + gbMovieTimes.Bounds.Height + 20, 400, 20);

            gbMovieSeats.Controls.Clear();

            if (currentPlanning != null && amountTickets > 0)
            {
                int rows = currentPlanning.zaal.rijen;
                int chairs = currentPlanning.zaal.zitting;
                int chairPerRow = chairs / rows;
                int[] takenSeats = MovieManager.GetManager().GetTakenSeats(currentMovie.naam, currentPlanning.datum, currentPlanning.tijd);
                int currentSeat = 1;
                int selectedChairs = 0;
                for (int y = 0; y < rows; y++)
                {
                    for (int x = 0; x < chairPerRow; x++)
                    {
                        CheckBox cbChair = new CheckBox();
                        cbChair.Text = currentSeat + "";
                        cbChair.Width = 45;
                        cbChair.Location = new Point(5 + (45 * x), 20 + (25 * y));
                        if (takenSeats.Contains(currentSeat))
                        {
                            cbChair.Checked = true;
                            cbChair.Enabled = false;
                        }
                        else if (!currentMovie.stoelen_kiezen)
                        {
                            if (amountTickets > selectedChairs)
                            {
                                cbChair.Checked = true;
                                selectedChairs++;                                
                            }
                        }
                        cbChair.CheckedChanged += cbChair_CheckedChanged;
                        gbMovieSeats.Controls.Add(cbChair);
                        currentSeat++;
                    }
                }

                string[] payTypes = new string[] { "cash", "pin", "bon", "abonnement", "10-kaart" };
                for (int i = 0; i < payTypes.Count(); i++)
                {
                    RadioButton rb = new RadioButton();
                    rb.Text = payTypes[i];
                    if (i % 2 == 0)
                    {
                        rb.Location = new Point(10 + (60 * i), 20 + (25 * rows));
                    }
                    else
                    {
                        rb.Location = new Point(10 + (60 * i), 45 + (25 * rows));
                    }
                    gbMovieSeats.Controls.Add(rb);
                }

                btnSave = new Button();
                btnSave.Text = "Betalen";
                btnSave.Location = new Point(370, 40 + (25 * rows));
                btnSave.Enabled = false;
                btnSave.Click += btnSave_Click;
                gbMovieSeats.Controls.Add(btnSave);

                if( !currentMovie.stoelen_kiezen)
                {
                    cbChair_CheckedChanged( null, EventArgs.Empty );
                }
            }
        }

        void cbChair_CheckedChanged(object sender, EventArgs e)
        {
            int checkedChairs = 0;

            foreach (Control control in gbMovieSeats.Controls)
            {
                if (control is CheckBox)
                {
                    CheckBox cb = (CheckBox)control;
                    if (cb.Enabled && cb.Checked)
                    {
                        checkedChairs++;
                    }
                }
            }

            if (checkedChairs == amountTickets)
            {
                btnSave.Enabled = true;
            }
            else
            {
                btnSave.Enabled = false;
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (getSelectedTickets().Count > 0)
            {
                bestelling currentOrder = new bestelling();
                currentOrder.active = true;
                currentOrder.afgehaald = true;
                currentOrder.betaald = true;
                currentOrder.kaartje = getSelectedTickets();
                currentOrder.soort = Enums.OrderType.koop.ToString();
                currentOrder.tijd = DateTime.Now.TimeOfDay;
                currentOrder.planning = currentPlanning;
                currentOrder.datum = DateTime.Today;

                int[] checkedChairs = new int[amountTickets];
                int currentChair = 0;
                foreach (Control control in gbMovieSeats.Controls)
                {
                    if (control is CheckBox)
                    {
                        CheckBox cb = (CheckBox)control;
                        if (cb.Enabled && cb.Checked)
                        {
                            checkedChairs[currentChair] = int.Parse(cb.Text);
                            currentChair++;
                        }
                    }
                }

                int i = 0;
                int rows = currentPlanning.zaal.rijen;
                int chairs = currentPlanning.zaal.zitting;

                double totalCost = 0;
                double discount = 0;
                double subscriptionDiscount = 0;

                foreach (kaartje ticket in currentOrder.kaartje)
                {
                    if (ticket.zittingnummer == null)
                    {
                        ticket.rijnummer = chairs / rows;
                        ticket.zittingnummer = checkedChairs[i];

                        totalCost += ticket.prijs;
                        //Eventueel voor abbonnemten
                        if (ticket.abbonement != null)
                        {
                            if (ticket.abbonement.kortingpercentage > 0)
                            {
                                subscriptionDiscount += (ticket.prijs * ((double)ticket.abbonement.kortingpercentage / 100));
                            }
                            else
                            {
                                subscriptionDiscount += (ticket.prijs - (double)ticket.abbonement.kortingpercentage);
                            }
                        }

                        i++;
                    }
                }

                totalCost = totalCost - subscriptionDiscount;
                totalCost = totalCost - discount;

                currentOrder.totaal_bedrag = totalCost;
                DatabaseManager.GetManager().SaveChanges();

                ReservationManager.GetManager().addReservation(currentOrder);
                MessageBox.Show("Klant heeft €" + totalCost.ToString("0.00") + " betaald\r\nSystem is tickets aan het printen\r\nEen ogenblik geduld a.u.b.\r\nticket-id: " + currentOrder.bestelling_id);
                for (i = 0; i < currentOrder.kaartje.Count; ++i)
                {
                    OutputManager.GetManager().createTicket(currentOrder.bestelling_id, currentOrder.kaartje.ToList()[i].kaartjeid);
                }
                MessageBox.Show("Tickets zijn klaar!");
                cbMovies.SelectedIndex = 0;
            }
        }

        private List<kaartje> getSelectedTickets()
        {
            List<kaartje> tickets = new List<kaartje>();

            selectedTickets = new kaartje[amountTickets];

            int current = 0;
            foreach( kaart_soort ticketType in TicketManager.GetManager().GetTicketTypes() )
            {
                foreach (Control control in gbMovieTickets.Controls)
                {
                    if (control is ComboBox)
                    {
                        ComboBox cb = (ComboBox)control;
                        if (cb.Name.Equals(ticketType.kaart_soort_naam) && !cb.Text.Equals("aantal tickets"))
                        {
                            for (int i = 0; i < int.Parse(cb.Text); i++)
                            {
                                kaartje ticket = new kaartje();
                                ticket.kaart_soort = ticketType;
                                selectedTickets[current] = ticket;
                                current++;
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < selectedTickets.Count(); i++)
            {
                kaartje ticket = selectedTickets[i];
                foreach (Control control in gbMovieSeats.Controls)
                {
                    if (control is CheckBox)
                    {
                        CheckBox cb = (CheckBox)control;
                        if (cb.Enabled && cb.Checked)
                        {
                            ticket.planning_id = currentPlanning.planning_id;

                            double price = getPriceForTicket(currentPlanning.film, ticket.kaart_soort);

                            ticket.prijs = price;

                            tickets.Add(ticket);
                        }
                    }
                }
            }

            return tickets;
        }

        private double getPriceForTicket(film film, kaart_soort ticketType)
        {
            double price = film.prijs;
            if (ticketType != null && ticketType.kortingpercentage != 0)
            {
                price = price * ((100 - (double)ticketType.kortingpercentage) / 100);
            }
            else
            {
                price = price - (double)ticketType.kortingbedrag;
            }

            return price;
        }

        private kaart_soort getTicketWithName(string name)
        {
            foreach (kaart_soort ticket in TicketManager.GetManager().GetTicketTypes())
            {
                if (ticket.kaart_soort_naam.Equals(name))
                {
                    return ticket;
                }
            }

            return null;
        }

        void MainForm_Disposed(object sender, EventArgs e)
        {
            rc.stop();
            reservationCheckThread.Join();

            Application.Exit();
        }
        #endregion
    }
}
